<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="40%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="产出设施" prop="facilityId">
                <el-select v-if="addEditFlag == 'add'" v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施"
                    @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
                <el-input v-if="addEditFlag == 'edit'" disabled v-model="ruleForm.facilityName"></el-input>
            </el-form-item>
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-if="addEditFlag == 'add'" v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次"
                    @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
                <el-input v-if="addEditFlag == 'edit'" disabled v-model="ruleForm.batchName"></el-input>
            </el-form-item>
            <el-form-item label="产出类型" prop="fishType">
                <el-select :disabled="addEditFlag == 'edit'" v-model="ruleForm.fishType" class="w100p" clearable
                    filterable placeholder="请选择类型" @change="handleChngeFishType">
                    <el-option label="活鱼" value="LIVE_FISH"></el-option>
                    <el-option label="次鱼" value="SECONDARY_FISH"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产出品种" prop="plantVarietyId">
                <el-select v-if="addEditFlag == 'add'" v-model="ruleForm.plantVarietyId" class="w100p" placeholder="请选择品种"
                    @change="getPlantVarietyName">
                    <el-option v-for="item, index in varietyList"
                        v-if="plantVarietyIdList.includes(item.plantVarietyId)" :key="index"
                        :label="item.plantVarietyName" :value="item.plantVarietyId"></el-option>
                </el-select>
                <el-input v-if="addEditFlag == 'edit'" disabled v-model="ruleForm.plantVarietyName"></el-input>
            </el-form-item>
            <el-form-item label="产出规格" prop="specificationId">
                <el-select v-model="ruleForm.specificationId" class="w100p" placeholder="请选择规格"
                    @change="getSpecificationName">
                    <el-option v-if="item.plantVarietyId == ruleForm.plantVarietyId"
                        v-for="item, index in specificationList" :key="index" :label="item.specificationName"
                        :value="item.specificationId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产出数量" prop="num">
                <el-input type="number" v-model="ruleForm.num" class="w100p" placeholder="请输入产出数量">
                    <template slot="append">粒</template>
                </el-input>
            </el-form-item>
            <el-form-item label="产出总量" prop="weight">
                <el-input type="number" v-model="ruleForm.weight" class="w100p" placeholder="请输入产出总量">
                    <template slot="append">斤</template>
                </el-input>
            </el-form-item>
            <el-form-item label="操作人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="getPersonName">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产出日期" prop="produceDate">
                <el-date-picker v-model="ruleForm.produceDate" value-format="yyyy-MM-dd" align="right" type="date"
                    @change="handkeChange" placeholder="选择日期" :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import outputManagment from '@/api/outputManagment/outputQuery.js';
import pondInformationManagement from '@/api/pondManagment/pondInformationManagement.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return []
            }
        },
        varietyList: {
            type: Array,
            default: () => {
                return []
            }
        },
        specificationList: {
            type: Array,
            default: () => {
                return []
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0 && value % 1 == 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的整数！'))
            }
        }
        let validatorNum10 = function (rule, value, callback) {
            if (value > 0 && value % 1 == 0 && value <= 10) {
                callback()
            } else {
                callback(new Error('请输入大于0小于10的整数！'))
            }
        }
        let validatorWeight = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            plantVarietyIdList: [],
            rules: {
                facilityId: [
                    { required: true, message: '请选择设施', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                fishType: [
                    { required: true, message: '请选择产出类型', trigger: 'change' }
                ],
                specificationId: [
                    { required: true, message: '请选择规格', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: validatorWeight, trigger: 'change' }
                ],
                produceDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ],
                plantVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择操作人', trigger: 'change' }
                ],
            }
        }
    },
    computed: {
        fishType() {
            return this.$store.state.initData.enum.fishType
        },
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        async queryByConditionPondInfo(id) {
            this.plantVarietyIdList = [];
            if (!id) return;
            try {
                const res = await pondInformationManagement.queryByCondition({ batchId: id });
                // 检查返回的状态码  
                if (res.code !== 1 && !res.data) {
                    return; // 如果状态码不是1，直接返回并不做后续处理  
                }
                let data = res.data || [];
                let inputPondDetailList = [];
                data.forEach(item => {
                    console.log(item.inputPondDetailList)
                    if (item.inputPondDetailList && item.inputPondDetailList.length > 0) {
                        inputPondDetailList = inputPondDetailList.concat(item.inputPondDetailList)
                    }
                });
                console.log(inputPondDetailList)
                // 如果inputPondDetailList存在且有数据，则处理数据  
                if (inputPondDetailList.length > 0) {
                    this.plantVarietyIdList = inputPondDetailList.map(item => item.plantVarietyId);
                } else {
                    this.$message.warning('请重新选择批次，该批次无投塘数据！')
                }
                console.log(this.plantVarietyIdList)
            } catch (error) {
                console.log(error);
            }
        },
        handkeChange(e) {
            console.log(e)
        },
        handleChngeFishType(type) {
            for (let key in this.fishType) {
                if (key == type) {
                    this.$set(this.ruleForm, 'fishTypeName', this.fishType[key]);
                }
            }
        },
        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
            this.queryByConditionPondInfo(this.ruleForm.batchId)
        },
        getPersonName() {
            let result = this.person.find(obj => obj.personNo == this.ruleForm.staffId);
            this.$set(this.ruleForm, 'staffName', result.person.name || "");
        },
        getSpecificationName() {
            let result = this.specificationList.find(obj => obj.specificationId == this.ruleForm.specificationId);
            this.$set(this.ruleForm, 'specificationName', result.specificationName || "");
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            console.log(result)
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchId', '');
            this.$set(this.ruleForm, 'batchName', '');
        },
        getPlantVarietyName() {
            let result = this.varietyList.find(obj => obj.plantVarietyId == this.ruleForm.plantVarietyId);
            console.log(result, this.facilityList)
            this.$set(this.ruleForm, 'plantVarietyName', result.plantVarietyName || "");
            this.$set(this.ruleForm, 'specificationId', '');
            this.$set(this.ruleForm, 'specificationName', '');
        },
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.addEditApi = outputManagment.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo || this.data.staffId,
                }
                this.addEditApi = outputManagment.edit
                this.addEditName = '编辑'
                this.queryByConditionPondInfo(this.data.batchId)
            }
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.line {
    border-bottom: 1px solid #e6e6e6;
}

.icon {
    font-size: 20px;
    line-height: 29px;
    cursor: pointer;
}

::v-deep .noLabel {
    .el-form-item {
        .label {
            display: none;
        }

        .el-form-item__content {
            margin: 0;
        }
    }
}
</style>